package com.ittx.dzt.tiktok.service;

import cn.hutool.core.collection.CollUtil;
import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.sys.response.Result;
import com.ittx.dzt.tiktok.constant.TiktokApiConstant;
import com.ittx.dzt.tiktok.handler.AbstractBaseTiktokApiHandler;
import lombok.extern.slf4j.Slf4j;
import open.constant.PlatformApiConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 查询可合单单号
 * <p>
 * cy.tiktok.packages.combinable.list
 * /fulfillment/202309/combinable_packages/search （查询可合单单号，非欧美地区合单发货使用）https://partner.tiktokshop.com/docv2/page/650aa481bace3e02b75d9e32?external_id=650aa481bace3e02b75d9e32
 * </p>
 *
 * @author gywang
 * @since 2024-07-26
 */
@Slf4j
@Service
public class TiktokOrderCombinableListService extends AbstractBaseTiktokApiHandler<String> {
    /**
     * 每页数量
     */
    private static final Integer PAGE_SIZE = 50;

    @Override
    public String getTiktokMethod() {
        return TiktokApiConstant.ORDER_COMBINABLE_PACKAGES_LIST;
    }

    @Override
    public String getLocalApiMethod() {
        return PlatformApiConstant.InboundInterface.SALES_ORDER_MERGE;
    }

    @Override
    public Result doProcess(PlatformApiParamDTO platformApiParamDTO, String s) {
        Result<?> validResult = checkShopCipherInfo(platformApiParamDTO);
        if (validResult.hasError()) {
            return validResult;
        }
        Map<String, Object> params = new HashMap<>();

        params.put("shop_cipher", getShopCipher(platformApiParamDTO));
        params.put("page_size", PAGE_SIZE);
        String nextToken = null;
        List<Map<String, Object>> list = new ArrayList<>();
        Result result = Result.success().addData(list);
        do {
            result = this.executeTiktokApi(getDefaultUrl(platformApiParamDTO.getStoreConfig()), platformApiParamDTO.getStoreConfig(), params, null, platformApiParamDTO.getRequestId(), TiktokApiConstant.ApiHttpMethod.GET);
            if (!result.isSuccess())
                return result;
            Map<String, Object> data = (Map<String, Object>) ((Map<String, Object>) result.getData()).get("data");
            nextToken = (String) data.get("next_page_token");
            List<Map<String, Object>> packs = (List<Map<String, Object>>) data.get("combinable_packages");
            if (CollUtil.isNotEmpty(packs))
                list.addAll(packs);
        } while (StringUtils.isNotBlank(nextToken));
        return Result.success().addData(list);
    }
}
